import { Device, GatewayType } from "@/api/interface/iot";
import { addRule, delRule, getRuleList } from "@/api/modules/iot/rule";
import Empty from "@/components/Empty";
import ProTable from "@/components/ProTable/index.vue";
import { ColumnProps } from "@/components/ProTable/interface";
import OnlineStatus from "@/components/Sansan/Status/OnlineStatus";
import { MessageType } from "@/enums/messageEnum";
import { RouterPath } from "@/enums/routerPath";
import { useAuthButtons } from "@/hooks/useAuthButtons";
import { dataFormat } from "@/utils/format";
import { confirm, showMsg, showTips } from "@/utils/util";
import { useRouter } from "vue-router";
import BasicDialog from "./components/detailDialog";
import SaveTorule from "./components/copyRule";
import "./rule.scss";
export default defineComponent({
	setup() {
		const router = useRouter();
		const initParam = reactive<Device.ReqRule>({});

		const dataCallback = (data: any) => {
			data.records.map((item: any) => {
				item.status = item.status + "";
				return item;
			});
			return {
				datalist: data.records,
				total: data.total || 0,
				pageIndex: data.current || 1,
				pageSize: data.size
			};
		};

		const getTableList = async (params: any) => {
			// return { result: { records: [{}] } };
			return getRuleList(params);
		};
		const buttonsList = ref<any>([]);
		onMounted(async () => {
			// 获取页面按钮权限
			buttonsList.value = await useAuthButtons();
		});
		const detailDialog = reactive<any>({
			title: "添加规则",
			detail: {},
			visible: false
		});
		const clickBtn = async (fn: string, row?: any) => {
			let selected: any[] = row ? row.selectList || [row] : [];
			switch (fn) {
				case "details":
					if (selected.length != 1) {
						showMsg("请选择一条记录", MessageType.warning);
						return;
					}
					router.push({ path: RouterPath.ruleDetail, query: { id: selected[0].id, type: selected[0].deviceType } });
					break;
				case "add":
					detailDialog.detail = {};
					detailDialog.visible = true;
					break;
				case "del":
					if (!selected.length) {
						showMsg("请选择要删除的数据", MessageType.warning);
						return;
					}
					confirm({ content: "删除后无法找回，确定删除当前选择的规则" }).then(flag => {
						flag && submitDel({ id: selected.map(item => item.id).join(",") });
					});
					break;
				case "copy":
					if (selected.length != 1) {
						showMsg("请选择一条要复制的规则记录", MessageType.warning);
						return;
					}
					copyruleDialog.visible = true;
					copyruleDialog.formData = JSON.parse(JSON.stringify(selected[0]));
					copyruleDialog.formData.id = selected[0].model;
					break;
			}
		};

		// 表格配置项
		const columns: ColumnProps[] = [
			{ type: "selection", fixed: "left", width: "auto" },
			{ prop: "name", label: "规则名称", search: { el: "input" } },
			// { prop: "status", label: "规则状态", search: { slot: {} } },
			{ prop: "deviceType", label: "设备", search: { slot: {} } },
			{ prop: "descript", label: "规则描述" },
			{ prop: "createTime", label: "创建时间" },
			{ prop: "operation", label: "操作", fixed: "right", width: 130 }
		];

		const proTable = ref<any>();
		const detail = ref<any>({});
		const submitDel = async (dataInfo: any) => {
			let res = await delRule({ ...dataInfo });
			let ok = showTips(res.code, "删除", res.message);
			if (ok) {
				proTable.value.clearSelection();
				proTable.value.reset();
			}
		};
		const submitAdd = async () => {
			detailDialog.detail.name = detailDialog.detail.name || detailDialog.detail.model;
			let res = await addRule({ ...detailDialog.detail });
			let ok = showTips(res.code, "添加", res.message);
			if (ok) {
				detailDialog.visible = false;
				proTable.value.getTableList();
			}
		};
		const copyruleDialog = reactive<any>({
			visible: false,
			formData: {}
		});
		const submitCopyrule = async (data: Device.ReqRule) => {
			let newrule = { ...copyruleDialog.formData };
			newrule.model = data.ruleModel;
			newrule.name = data.ruleName;
			delete newrule.id;
			let { code, result, message } = await addRule(newrule);
			let ok = showTips(code, "复制规则", message);
			let res = result as any;
			if (ok && res) {
				copyruleDialog.visible = false;
				proTable.value.getTableList();
			}
		};
		return () => {
			return (
				<div>
					<SaveTorule
						title="复制规则"
						v-model:visible={copyruleDialog.visible}
						formData={copyruleDialog.formData}
						onSubmit={(data: Device.ReqRule) => submitCopyrule(data)}
					></SaveTorule>
					<BasicDialog
						width="600px"
						title={detailDialog.title}
						v-model:visible={detailDialog.visible}
						detail={detail.value}
						onSubmit={() => submitAdd()}
					></BasicDialog>
					<ProTable
						ref={proTable}
						title={buttonsList.value.length ? "" : "规则管理"}
						columns={columns}
						requestApi={getTableList}
						initParam={initParam}
						dataCallback={dataCallback}
						searchCol={5}
						toolbar={["grid"]}
						viewType="grid"
						gridSpan={8}
					>
						{{
							"search-status": () => {
								return (
									<el-select v-model={initParam.status} style="width:100px">
										<el-option label="全部" value=""></el-option>
										<el-option label="启用" value={true}></el-option>
										<el-option label="禁用" value={false}></el-option>
									</el-select>
								);
							},
							"search-deviceType": () => {
								return (
									<el-select v-model={initParam.deviceType} style="width:100px">
										<el-option label="全部" value=""></el-option>
										<el-option label="设备" value={GatewayType.Device}></el-option>
										<el-option label="软网关" value={GatewayType.SoftGateway}></el-option>
										<el-option label="网关设备" value={GatewayType.Gateway}></el-option>
									</el-select>
								);
							},
							tableHeader: (scope: any) => {
								return buttonsList.value?.map((item: any) => {
									return (
										<el-button onClick={() => clickBtn(item.path, scope)} type={item.btnClass}>
											<i class={`iconfont ${item.icon}`}></i>
											{item.menuName}
										</el-button>
									);
								});
							},
							cardBody: (scope: any) => {
								return (
									<div class="rule-card shadow-md">
										<div class="title flex justify-between">
											<el-link title="查看规则详情" type="primary" onClick={() => clickBtn("details", scope.row)}>
												<div class="master-title">{scope.row.name || "变量转换规则"}</div>
											</el-link>
											<div class="time">{dataFormat("datetime", scope.row.createTime)}</div>
										</div>
										<div class="body">
											<div class="block">
												<div class="flex">
													<div class="label">规则名称</div>
													<div class="text">{scope.row.name}</div>
												</div>
												<div class="flex">
													<div class="label">输入数据</div>
													<div class="text">{scope.row.deviceType}</div>
												</div>
												<div class="flex">
													<div class="label">规则说明</div>
													<div class="text">{scope.row.model}</div>
												</div>
											</div>
										</div>
										<div class="footer flex justify-between">
											<el-button
												class="flex-1 iconfont icontrash-2"
												link
												type="danger"
												disabled={buttonsList.value.find((item: any) => item.path == "del") ? false : true}
												onClick={() => clickBtn("del", scope.row)}
											>
												删除规则
											</el-button>
											<el-button
												class="flex-1 iconfont iconsettings"
												link
												title="查看规则详情"
												type="primary"
												onClick={() => clickBtn("details", scope.row)}
											>
												规则配置
											</el-button>
										</div>
									</div>
								);
							},
							status: (scope: any) => {
								return <OnlineStatus v-model={scope.row.status} onlineLabel="启用" offlineLabel="停用" />;
							},
							model: (scope: any) => {
								return (
									<el-link type="primary" onClick={() => clickBtn("details", scope.row)}>
										{scope.row.model}
									</el-link>
								);
							},
							createTime: (scope: any) => {
								return dataFormat("datetime", scope.row.createTime);
							},
							operation: (scope: any) => {
								return (
									<>
										<el-link
											type="primary"
											link
											class="iconfont iconbx-file"
											onClick={() => {
												clickBtn("details", scope.row);
											}}
										>
											详情
										</el-link>
									</>
								);
							},
							empty: () => {
								return (
									<Empty
										class="text-left leading-6"
										subtitle="将一些复杂易变的业务逻辑从代码编程可视化页面标记，配置出入参，逻辑条件，减少开发和对应产生的逻辑错误，让最懂业务运营人员掌握业务逻辑。"
										btnText="添加规则"
										onAdd={() => clickBtn("add")}
									/>
								);
							}
						}}
					</ProTable>
				</div>
			);
		};
	}
});
